package service

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"net/http"
	"time"
	"vpn/app/global"
	"vpn/app/global/consts"
	"vpn/app/utils/file_handle"
	"vpn/app/utils/jwt_token"
	"vpn/app/utils/response"
)

type UserInfo struct {
	Name     string `json:"name"`
	PassWord string `json:"password"`
}

func CreateJwtToken(username string) (string, error) {
	// 生成 JWT Token
	customClaims := jwt_token.CustomClaims{
		UserName: username,
		// 特别注意，针对前文的匿名结构体，初始化的时候必须指定键名，并且不带 jwt. 否则报错：Mixture of field: value and value initializers
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 10,                         // 生效开始时间
			ExpiresAt: time.Now().Unix() + global.JwtConf.JwtExpireAt, // 失效截止时间
		},
	}
	return customClaims.CreateToken()
}

func SetJwtToken(context *gin.Context, username string) {
	token, err := CreateJwtToken(username)
	if err != nil {
		log.Error(err.Error())
		response.Fail(context, http.StatusInternalServerError, "生成 Token 失败", gin.H{"error": err.Error()})
		return
	}
	context.Writer.Header().Set("token", token)
}

func GetUserPassword(filePath string) (pwd string) {
	if exist, _ := file_handle.Exists(filePath); !exist {
		return consts.InitUserPwd
	}
	userInfo := UserInfo{}
	if err := file_handle.ReadJsonFile(filePath, &userInfo); err != nil {
		log.Error(err.Error())
	}
	if userInfo.PassWord != "" {
		pwd = userInfo.PassWord
	} else {
		pwd = consts.InitUserPwd
	}
	return pwd
}
